package com.ds.robot.assistant.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
// @Configuration
@Slf4j
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("RedisTemplate init redisConnectionFactory: {}", redisConnectionFactory);
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 配置 objectMapper
        configureObjectMapper(objectMapper);
        jacksonSerializer.setObjectMapper(objectMapper);

        // 设置键的序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        // 设置 value 和 hash value 的序列化规则
        template.setValueSerializer(jacksonSerializer);
        template.setHashValueSerializer(jacksonSerializer);
        // 必须调用afterPropertiesSet()方法，否则序列化可能会出现问题
        template.afterPropertiesSet();
        return template;
    }

    private void configureObjectMapper(ObjectMapper objectMapper) {
        // 忽略空字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 忽略空集合
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        // 启用好看的打印（可选）
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        // 注册 JavaTimeModule 以支持 Java 8 日期和时间类型
        objectMapper.registerModule(new JavaTimeModule());
        // 其他配置
    }
}
